package com.crl.net
{
	import com.crl.game.simulation.common.BaseSimulation;
	import com.crl.game.simulation.server.decoder.IServerRouter;
	
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;

	public class SocketDelegate
	{
		private var buffer:ByteArray;
		
		private var socket:Socket;
		
		
		public var onData:Function;
		public function SocketDelegate(socket:Socket)
		{
			buffer=new ByteArray();
			
			this.socket=socket;

			this.socket.addEventListener(ProgressEvent.SOCKET_DATA,socketDataHandler);
		}
		
		private var msgLength:int;
		private function socketDataHandler(event:ProgressEvent):void{
			while(true){
				if(msgLength==0){
					if(socket.bytesAvailable<4)return;
					msgLength=socket.readInt();
				}
				
				if(msgLength==0)return;
				
				if(socket.bytesAvailable>=msgLength){
					buffer.clear();
					socket.readBytes(buffer,0,msgLength);
					msgLength=0;
					
					onData(buffer.readInt(),buffer.readObject());
					//simulation.reticept(buffer.readInt(),buffer.readObject(),_id);
				}
			}
		}
		
		private var sendBuffer:ByteArray=new ByteArray();
		public function send(code:int,data:*):void{
			sendBuffer.clear();
			sendBuffer.writeInt(code);
			sendBuffer.writeObject(data);
			sendBuffer.position=0;
			
			var len:int=sendBuffer.length;
			socket.writeInt(len);
			socket.writeBytes(sendBuffer,0,len-1);
		}
		
	}
}